package net.wanho.service.impl;

import io.swagger.models.auth.In;
import net.wanho.contant.UserConstant;
import net.wanho.mapper.PermissionMapper;
import net.wanho.po.Permission;
import net.wanho.po.Role;
import net.wanho.mapper.RoleMapper;
import net.wanho.service.RoleService;
import net.wanho.vo.PermVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author 汤小洋
 * @since 2025-09-25
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService {

    private final RoleMapper roleMapper;
    private final RedisTemplate<String, Object> redisTemplate;
    private final PermissionMapper permissionMapper;

    /**
     * 角色表分页查询
     * @param pageNum
     * @param pageSize
     * @param role
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageInfo findPage(int pageNum, int pageSize, Role role) {
        if(ObjectUtil.isNull(role)){
            role = new Role();
        }

        // 分页
        PageHelper.startPage(pageNum,pageSize);
        List<Role> roleList = roleMapper.select(role);
        return new PageInfo(roleList);
    }

    /**
     * 根据主键查询角色表
     * @param roleId
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public Role findById(Serializable roleId) {
        return roleMapper.selectById(roleId);
    }

    /**
     * 角色表新增
     * @param role
     */
    @Override
    public void add(Role role) {
        roleMapper.insert(role);
    }

    /**
     * 修改角色表
     * @param role
     */
    @Override
    public void modify(Role role) {
        roleMapper.update(role);
    }

    /**
     * 根据主键删除角色表
     * @param roleId
     */
    @Override
    public void removeById(Serializable roleId) {
        if(((String)roleId).contains(",")){
            roleMapper.deleteByIds(((String)roleId).split(","));
        }else {
            roleMapper.deleteById(roleId);
        }
    }

    @Override
    public void grant(Integer roleId, String rids) {
        Role role = new Role();
        role.setRoleId(roleId);
        role.setPsIds(rids);
        roleMapper.update(role);

        redisTemplate.delete(redisTemplate.keys(UserConstant.MENU_PREFIX+"*"));
    }

    @Override
    public List<PermVo> removeRight(Integer roleId, Integer rightId) {
        // 获取要删除的权限及子权限
        List<Integer> deleteRightIds = new ArrayList<>();
        deleteRightIds.add(rightId);
        findPermission(rightId, deleteRightIds);

        // 获取当前角色现有的权限
        String[] allRightIds = roleMapper.selectById(roleId).getPsIds().split(",");

        // 计算删除后的权限id
        String ids = Arrays.stream(allRightIds)
                .filter(item -> !deleteRightIds.contains(Integer.parseInt(item)))
                .collect(Collectors.joining(","));

        // 更新权限
        roleMapper.updatePermission(roleId, ids);

        // 获取当前权限的权限


        return null;
    }

    /**
     * 递归查询权限及子权限
     * @param rightId
     * @param deleteRightIds
     */
    private void findPermission(Integer rightId, List<Integer> deleteRightIds) {
        List<Permission> perms = permissionMapper.selectChildrenByPid(rightId);
        perms.forEach(item -> {
            deleteRightIds.add(item.getPsId());
            // 递归
            findPermission(item.getPsId(), deleteRightIds);
        });
    }
}
